const http = require('../../network/http')
const api = require('../../network/api')
var util = require('../../utils/dateTime.js');

// pages/detail/detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detailId: '',
    showCancel: false,
    showDelay: false,
    showExtend: false,
    showRoom: false, //房间操作弹窗
    showFinish: false,
    storeId: '',
    cancelStatus: '',
    showWechat: false,
    extendArray:[['00', '01', '02', '03', '04'], ['10', '20', '30', '40', '50']],
    extendIndex: [0, 2],
    openStartTime: '',
    detail: {},
    roomcancheckList: {},
    choseRoomSelect: {},
    leaveTime: '',
    memberId: '',
    mobile: '',
  },

  loadBusinessData() {
    http.request({
      showLoading: true,
      url: api.loadTradeDetail,
      data: {
        tradeId: this.data.detailId
      },
    }).then(res => {
      if (res.data.code == 200) {
        this.setData({
          'detail': res.data.result,
        })
        if(res.data.result.payInfos.length == 1){
          if(res.data.result.payInfos[0].payMode == 1){
            this.setData({
              showWechat: true,
            })
          }else{
            this.setData({
              showWechat: false,
            })
          }
        }
      }
    }).catch(err => {
      console.log(err)
    });
  },

  closeview : function(e){
    wx.navigateBack({
      delta: 1,
    })
  },
  preventTouchMove:function(e) {

  },
  cancelOrder(e) {
    this.setData({
      showCancel: true,
      cancelStatus: '1',
    })
  },
  cancelOrderUse(e) {
    this.setData({
      showCancel: true,
      showWechat: false,
    })
  },
  finishOrder(e) {
    this.setData({
      showFinish: true,
    })
  },
  delayOrder(e) {
    // var openStartTImeFull = util.formatTime(new Date());
    var openStartTImeFull = this.haveSomeMinutesTime(15);
    var openStartTime = openStartTImeFull.substring(0, 16);
    this.setData({
      showDelay: true,
      openStartTime: openStartTime,
    })
  },
  extendOrder(e) {
    this.setData({
      showExtend: true,
    })
  },
  hiddenCancel(e) {
    this.setData({
      showCancel: false,
      showDelay: false,
      showExtend: false,
      showRoom: false,
      showFinish: false,
      showCoupon: false,
    })
  },
  weChatCancel(e){
    this.setData({
      cancelStatus: '1',
    })
  },
  remainingCancel(e){
    this.setData({
      cancelStatus: '2',
    })
  },
  couponCancel(e){
    this.setData({
      cancelStatus: '3',
    })
  },
  confirmCancel(e){
    if(this.data.detail.state == 2){
      this.cancelRequest("");
    }else{
      if(this.data.detail.payInfos[0].payMode == 1){
        if(this.data.cancelStatus == 1){
          this.cancelRequest('1');
        }else if(this.data.cancelStatus == 2){
          this.cancelRequest('2');
        }else if(this.data.cancelStatus == 3){
          this.goToCoupon('3');
        }
      }else if(this.data.detail.payInfos[0].payMode == 3 || this.data.detail.payInfos[0].payMode == 5){
        this.cancelRequest('1');
      }else{
        this.goToCoupon('3');
      }
    }
    
  },
  confirmDelay(e){
    var startDate = this.data.openStartTime + ":00";
    var reserveDate = this.data.openStartTime.substring(0,10);
    http.request({
      showLoading: true,
      shake: true,
      url: api.reserveTime,
      method: "POST",
      data: {
        startDate: startDate,
        reserveDate: reserveDate,
        tradeId: this.data.detailId
      },
    }).then(res => {
      if (res.data.code == 200) {
        this.hiddenCancel();
        setTimeout(function () {
          wx.showToast({
            title: '更改订单时间成功',
            icon: "none",
            duration: 2000
          });
        }, 500);
        wx.navigateBack({
          delta: 1,
        })
      }else{
        setTimeout(function () {
          wx.showToast({
            title: res.data.message,
            icon: "none",
            duration: 2000
          });
        }, 500);
      }
    }).catch(err => {
      console.log(err)
    });
  },
  confirmExtend(e){
    var startDate = this.data.detail.reserveStartTime + ":00";
    var reserveDate = this.data.detail.reserveStartTime.substring(0,10);
    var durationTime = this.data.extendArray[0][this.data.extendIndex[0]] * 60 + this.data.extendArray[1][this.data.extendIndex[1]]*1;
    console.log("durationTime**********" + durationTime);
    http.request({
      showLoading: true,
      shake: true,
      url: api.renewalTrade,
      method: "POST",
      data: {
        startDate: startDate,
        reserveDate: reserveDate,
        tradeId: this.data.detailId,
        durationTime: durationTime
      },
    }).then(res => {
      if (res.data.code == 200) {
        this.hiddenCancel();
        setTimeout(function () {
          wx.showToast({
            title: '订单续时成功',
            icon: "none",
            duration: 2000
          });
        }, 500);
        wx.navigateBack({
          delta: 1,
        })
      }else{
        setTimeout(function () {
          wx.showToast({
            title: res.data.message,
            icon: "none",
            duration: 2000
          });
        }, 500);
      }
    }).catch(err => {
      console.log(err)
    });
  },
  cancelRequest(mode){
    http.request({
      showLoading: true,
      shake: true,
      url: api.cancelTrade,
      method: "POST",
      data: {
        cancelMode: mode,
        tradeId: this.data.detailId
      },
    }).then(res => {
      if (res.data.code == 200) {
        this.hiddenCancel();
        setTimeout(function () {
          wx.showToast({
            title: '订单取消成功',
            icon: "none",
            duration: 2000
          });
        }, 500);
        wx.navigateBack({
          delta: 1,
        })
      }else{
        setTimeout(function () {
          wx.showToast({
            title: '订单取消失败，请稍后再试',
            icon: "none",
            duration: 2000
          });
        }, 500);
      }
    }).catch(err => {
      console.log(err)
    });
  },
  goToCoupon(mode){
    wx.navigateTo({
      url: '/pages/backCoupon/backCoupon?storeId=' + this.data.storeId + "&detailId=" + this.data.detailId,
    })
  },
  extendChange(e){
    console.log('picker加时发送选择改变，携带值为', e.detail.value)
    this.setData({
      extendIndex: e.detail.value
    })
  },
  extendColumnChange(e){
    console.log('picker加时修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      extendArray: this.data.extendArray,
      extendIndex: this.data.extendIndex
    };
    data.extendIndex[e.detail.column] = e.detail.value;
    if(e.detail.column == 0){
      if(data.extendIndex[0] == 0){
        data.extendArray[1] = ['10', '20', '30', '40', '50'];
      }else if(data.extendIndex[0] == 4){
        data.extendArray[1] = ['00'];
      }else{
        data.extendArray[1] = ['00', '10', '20', '30', '40', '50'];
      }
      data.extendIndex[1] = 0;
      console.log(data.extendIndex);
      this.setData(data);
    }
  },

  haveSomeMinutesTime :function(n) {
    if (n == null) {
      n = 0;
    }
    // 时间
    var newDate = new Date()
    // var timeStamp = newDate.getTime(); //获取时间戳
    var date = newDate.setMinutes(newDate.getMinutes() + n);
    newDate = new Date(date);
    var year = newDate.getFullYear();
    var month = newDate.getMonth() + 1;
    var day = newDate.getDate();
    var h = newDate.getHours();
    var m = newDate.getMinutes();
    var s = newDate.getSeconds();
    if (month < 10) {
      month = '0' + month;
    };
    if (day < 10) {
      day = '0' + day;
    };
    if (h < 10) {
      h = '0' + h;
    };
    if (m < 10) {
      m = '0' + m;
    };
    if (s < 10) {
      s = '0' + s;
    };
    var time = year + '-' + month + '-' + day + ' ' + h + ':' + m + ':' + s;
    return time;
  },
  onPickerChange: function (e) {
    var openStartTime = e.detail.dateString;
    this.setData({
      openStartTime: openStartTime,
    })
   },
   windRoom: function (e) {
    http.request({
      showLoading: true,
      url: api.commutativeItemList,
      data: {
        id: this.data.detailId,
        type: 2,
      },
    }).then(res => {
      if (res.data.code == 200 && res.data.result != null) {
        this.setData({
          'roomcancheckList': res.data.result,
          showRoom: true,
        })
      } else {
        wx.showToast({
          title: '服务器异常，返回空列表',
          icon: "none",
          duration: 2000
        })
        this.setData({
          'roomcancheckList': '',
          showRoom: true,
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err,
        icon: "none",
        duration: 2000
      });
      this.setData({
        choseRoomSelect: {},
      });
    });
   },
   changeRoomChoose: function (e) {
    var $data = e.currentTarget.dataset;
    this.setData({
      choseRoomSelect: $data.bean,
    });
  },
    /**
   * 更换房间
   */
  changeRoom() {
    http.request({
      showLoading: true,
      shake: true,
      url: api.changeTradeItem,
      data: {
        itemId: this.data.choseRoomSelect.itemId,
        originalId: this.data.detailId,
        type: 2,
      },
    }).then(res => {
      if (res.data.code == 200) {
        if (res.data.success) {
          setTimeout(function () {
            wx.showToast({
              title: '换包成功',
              icon: "none",
              duration: 2000
            });
          }, 1000);
          wx.navigateBack({
            delta: 1,
          })
        } else {
          setTimeout(function () {
            wx.showToast({
              title: '换包失败,请稍后再试',
              icon: "none",
              duration: 2000
            });
          }, 1000);
        }
      }
    }).catch(err => {
      setTimeout(function () {
        wx.showToast({
          title: err,
          icon: "none",
          duration: 2000
        });
      }, 1000);
    });
  },
  confirmFinish: function (e) {
    http.request({
      showLoading: true,
      shake: true,
      url: api.requestFinish,
      method: "POST",
      data: {
        tradeId: this.data.detailId
      },
    }).then(res => {
      if (res.data.code == 200) {
        if(res.data.result.completeState){
          this.hiddenCancel();
          setTimeout(function () {
            wx.showToast({
              title: '订单完成',
              icon: "none",
              duration: 2000
            });
          }, 500);
          wx.navigateBack({
            delta: 1,
          })
        }else if(res.data.result.needGive){
          this.setData({
            leaveTime: res.data.result.remainderTime,
            memberId: res.data.result.memberId,
            showFinish: false,
            showCoupon: true
          })
        }
        
      }else{
        setTimeout(function () {
          wx.showToast({
            title: '操作失败，请稍后再试',
            icon: "none",
            duration: 2000
          });
        }, 500);
      }
    }).catch(err => {
      console.log(err);
      setTimeout(function () {
        wx.showToast({
          title: err,
          icon: "none",
          duration: 2000
        });
      }, 1000);
    });
  },
  doFinish: function (e) {
    http.request({
      showLoading: true,
      shake: true,
      url: api.doFinish,
      method: "POST",
      data: {
        tradeId: this.data.detailId,
        isGive: false
      },
    }).then(res => {
      if (res.data.code == 200) {
        if(res.data.result){
          this.hiddenCancel();
          setTimeout(function () {
            wx.showToast({
              title: '订单完成',
              icon: "none",
              duration: 2000
            });
          }, 500);
          wx.navigateBack({
            delta: 1,
          })
        }else{
          setTimeout(function () {
            wx.showToast({
              title: '操作失败，请稍后再试',
              icon: "none",
              duration: 2000
            });
          }, 500);
        }
      }else{
        setTimeout(function () {
          wx.showToast({
            title: '操作失败，请稍后再试',
            icon: "none",
            duration: 2000
          });
        }, 500);
      }
    }).catch(err => {
      console.log(err);
      setTimeout(function () {
        wx.showToast({
          title: err,
          icon: "none",
          duration: 2000
        });
      }, 1000);
    });
  },
  goFinishCoupon(e){
    wx.navigateTo({
      url: '/pages/finishCoupon/finishCoupon?storeId=' + this.data.storeId + "&detailId=" + this.data.detailId + "&memberId=" + this.data.memberId,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    console.log(options);
    that.setData({
      detailId: options.detailId,
      storeId: options.storeId,
      mobile: wx.getStorageSync('phoneNum'),
    })
    that.loadBusinessData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})